<template>
	<div class="app-container">
		<div class="filter-container">
			<el-input v-model="listQuery.userCode" placeholder="请输入用户编号" style="width: 200px;" class="filter-item"
				@keyup.enter.native="handleFilter" />
			<el-input v-model="listQuery.userName" placeholder="请输入用户名称" style="width: 200px;" class="filter-item"
				@keyup.enter.native="handleFilter" />
			<el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
				查询
			</el-button>
			<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
				@click="handleCreate">
				新增
			</el-button>
			<el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
				@click="handleDownload">
				导出
			</el-button>
			<el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;"
				@change="tableKey=tableKey+1">
				密码
			</el-checkbox>
		</div>

		<el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
			style="width: 100%;" @sort-change="sortChange">
			<el-table-column label="ID" prop="id" sortable="custom" align="center" width="60"
				:class-name="getSortClass('id')">
				<template slot-scope="{row}">
					<span>{{ row.id }}</span>
				</template>
			</el-table-column>
			<el-table-column label="用户编码" width="100px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.userCode }}</span>
				</template>
			</el-table-column>

			<el-table-column label="用户名称" width="100px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.userName }}</span>
				</template>
			</el-table-column>
			<el-table-column label="角色类型" width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.userType }}</span>
				</template>
			</el-table-column>
			<el-table-column label="创建者" width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.createdBy }}</span>
				</template>
			</el-table-column>
			<el-table-column label="创建时间" min-width="150px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.creationDate }}</span>
				</template>
			</el-table-column>
			<el-table-column label="更新者" width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.modifyBy }}</span>
				</template>
			</el-table-column>
			<el-table-column label="更新时间" min-width="150px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.modifyDate }}</span>
				</template>
			</el-table-column>
			<el-table-column v-if='showReviewer' label="密码" width="80px" align="center">
				<template slot-scope="{row}">
					<span style="color:red;">{{ row.userPassword }}</span>
				</template>
			</el-table-column>

			<el-table-column label="图像" width="80px" align="center">
				<template slot-scope="{row}">
					<span><img src='row.picPath' /></span>
				</template>
			</el-table-column>
			<el-table-column label="状态" class-name="status-col" prop='status' :formatter='statusFormatter' width="80">
				<!-- <template slot-scope="{row}">
					<el-tag :type="row.status | statusFilter">
						{{ row.status }}
					</el-tag>
				</template> -->
			</el-table-column>

			<el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
				<template slot-scope="{row,$index}">
					<el-button type="primary" size="mini" @click="handleUpdate(row)">
						编辑
					</el-button>
					<el-button v-if="row.status!='Y'" size="mini" type="success"
						@click="handleModifyStatus(row,row.status)">
						启用
					</el-button>
					<el-button v-if="row.status!='N'" size="mini" @click="handleModifyStatus(row,row.status)">
						禁用
					</el-button>
					<el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
			@pagination="getList" />

		<!-- 抽屉模态框 -->
		<el-drawer :title="dr_title" :visible.sync="dialog" :before-close="handleClose" direction="rtl"
			custom-class="demo-drawer" size="35%">
			<div class="demo-drawer__content">
				<el-form :model="form" ref="form" :rules="rules">
					<el-form-item v-if='show_id_item' label="编号ID" :label-width="formLabelWidth">
						<el-input v-model="form.id" :readonly='true'></el-input>
					</el-form-item>
					<el-form-item label="用户编码" :label-width="formLabelWidth" prop="userCode">
						<el-input v-model="form.userCode"></el-input>
					</el-form-item>
					<el-form-item label="用户名称" :label-width="formLabelWidth" prop="userName">
						<el-input v-model="form.userName"></el-input>
					</el-form-item>
					<el-form-item label="角色类型" :label-width="formLabelWidth" prop="userType">
						<el-select v-model="form.userType" placeholder="请选择角色类型" filterable>

							<el-option :label="item.valueName" :value="item.valueId" v-for="(item,index) in dictData"
								:key="index"></el-option>
							<!-- <el-option label="管理员" value="1"></el-option>
							<el-option label="开发者" value="2"></el-option>
							<el-option label="员工" value="3"></el-option> -->
						</el-select>
					</el-form-item>
					<el-form-item label="用户密码" :label-width="formLabelWidth" prop="userPassword">
						<el-input v-model="form.userPassword"></el-input>
					</el-form-item>
					<el-form-item label="用户图像" :label-width="formLabelWidth">
						<el-input v-model="form.picPath"></el-input>
						<input type="file" @change="handleUpload" ref="inputer" accept="application/vnd.ms-powerpoint,
													application/vnd.openxmlformats-officedocument.presentationml.presentation, 
													application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, 
													application/pdf">
						<img v-if="picUrl" :src="picUrl" class="avatar" />

						<!-- <el-upload class="avatar-uploader" action="" :show-file-list="false" :on-change="picturePreview"
							:auto-upload="false">
							<img v-if="imageUrl" :src="imageUrl" class="avatar" />
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
						<el-button type="warning" class="cancelBtn" v-show="imageUrl"
							@click="cancelUpload">取消图片</el-button>
						<el-button style="margin-left: 10px;" size="small" type="success"
							@click="submitUpload">上传到服务器</el-button> -->
					</el-form-item>
					<el-form-item label="状态" :label-width="formLabelWidth">
						<el-select v-model="form.status" placeholder="请选择状态">
							<el-option label="启用" value="Y"></el-option>
							<el-option label="禁用" value="N"></el-option>
						</el-select>
					</el-form-item>
				</el-form>
				<div class="demo-drawer__footer">
					<el-button icon="el-icon-error" @click="cancelForm">取 消</el-button>
					<el-button icon="el-icon-refresh-right" type="warning" @click="resetForm('form')">重置</el-button>
					<el-button icon="el-icon-check" type="success" @click="handleClose('form')"
						:loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
				</div>
			</div>
		</el-drawer>


		<el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
			<el-table :data="pvData" border fit highlight-current-row style="width: 100%">
				<el-table-column prop="key" label="Channel" />
				<el-table-column prop="pv" label="Pv" />
			</el-table>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		fetchList,
		del,
		updateStatus,
		add,
		update,
		uploadImg,
		fetchPv,
		createArticle,
		updateArticle
	} from '@/api/backendApi';

	import {
		fetchDictList
	} from '@/api/dictApi'

	import waves from '@/directive/waves' // waves directive
	import {
		parseTime
	} from '@/utils'

	import {
		getToken
	} from '@/utils/auth'

	import Pagination from '@/components/Pagination' // secondary package based on el-pagination

	const calendarTypeOptions = [{
			key: 'CN',
			display_name: 'China'
		},
		{
			key: 'US',
			display_name: 'USA'
		},
		{
			key: 'JP',
			display_name: 'Japan'
		},
		{
			key: 'EU',
			display_name: 'Eurozone'
		}
	]

	// arr to obj, such as { CN : "China", US : "USA" }
	const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
		acc[cur.key] = cur.display_name
		return acc
	}, {})

	export default {
		name: 'ComplexTable',
		components: {
			Pagination
		},
		directives: {
			waves
		},
		filters: {
			statusFilter(status) {
				const statusMap = {
					Y: 'success',
					N: 'danger'
				}
				return statusMap[status]
			},
			typeFilter(type) {
				return calendarTypeKeyValue[type]
			}
		},
		data() {
			return {
				tableKey: 0,
				list: null,
				total: 0,
				listLoading: true,
				listQuery: {
					pageNo: 1,
					pageSize: 20,
					userCode: '',
					userName: '',
					sort: '+id'
				},
				importanceOptions: [1, 2, 3],
				calendarTypeOptions,
				sortOptions: [{
					label: 'ID Ascending',
					key: '+id'
				}, {
					label: 'ID Descending',
					key: '-id'
				}],
				statusOptions: ['published', 'draft', 'deleted'],
				showReviewer: false,
				temp: {
					id: undefined,
					importance: 1,
					remark: '',
					timestamp: new Date(),
					title: '',
					type: '',
					status: 'published'
				},
				dialogFormVisible: false,
				dialogStatus: '',
				textMap: {
					update: '编辑',
					create: '新增'
				},
				dialogPvVisible: false,
				pvData: [],
				rules: {
					userCode: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					userName: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					userPassword: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					userType: [{
						required: true,
						message: '必填字段',
						trigger: 'change'
					}]
				},
				downloadLoading: false,
				dialog: false,
				loading: false,
				form: {
					id: '',
					userCode: '',
					userName: '',
					userType: '',
					userPassword: '',
					picPath: '',
					status: '',
					createdBy: '',
					creationDate: '',
					modifyBy: '',
					modifyDate: ''
				},
				formLabelWidth: '80px',
				dr_title: '',
				show_id_item: false,
				dictData: [],
				file: "",
				imageUrl: "",
				picUrl: ''
			}
		},
		created() {
			this.getList();

		},
		methods: {
			getList() {
				this.listLoading = true
				fetchList(this.listQuery).then(response => {
					console.info('response==>', response)
					this.list = response.data.records;
					this.total = response.data.total;

					// Just to simulate the time of the request
					setTimeout(() => {
						this.listLoading = false
					}, 1.5 * 1000)
				})
			},
			/* 格式状态 */
			statusFormatter(row, column, cellValue, index) {
				return cellValue == 'Y' ? '已启用' : '已禁用';
			},
			handleFilter() {
				this.listQuery.page = 1
				this.getList()
			},
			handleModifyStatus(row, _status) {
				console.info('row=>', row)
				console.info('status=>', status);
				this.$confirm('此操作将更改编号为' + row.id + '的数据状态, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					updateStatus({
						id: row.id,
						status: _status
					}).then(res => {
						if (res.code == '201') {
							this.$message({
								type: 'success',
								message: res.msg
							});
							this.getList();
						} else {
							this.$message({
								type: 'error',
								message: res.msg
							});
						}

					}).catch(err => {
						this.$message({
							type: 'error',
							message: '操作异常，请联系管理员！'
						});
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			sortChange(data) {
				const {
					prop,
					order
				} = data;
				if (prop === 'id') {
					this.sortByID(order)
				}
			},
			sortByID(order) {
				if (order === 'ascending') {
					this.listQuery.sort = '+id'
				} else {
					this.listQuery.sort = '-id'
				}
				this.handleFilter()
			},
			resetTemp() {
				this.temp = {
					id: undefined,
					importance: 1,
					remark: '',
					timestamp: new Date(),
					title: '',
					status: 'published',
					type: ''
				}
			},
			handleCreate() {
				this.dr_title = '新增数据';
				this.dialog = true;
				this.show_id_item = false;
				this.clearForm();
				this.getDictList();
			},
			clearForm() {
				this.form = {
					id: '',
					userCode: '',
					userName: '',
					userType: '',
					userPassword: '',
					picPath: '',
					status: 'N'
				}
				this.picUrl = '';
			},

			handleUpdate(row) {
				this.dr_title = '编辑数据';
				this.dialog = true;
				this.show_id_item = true;
				console.info('row=>', row);
				this.clearForm();
				this.form = {
					id: row.id,
					userCode: row.userCode,
					userName: row.userName,
					userType: row.userType,
					userPassword: row.userPassword,
					picPath: row.picPath,
					status: row.status
				};
				this.getDictList();
			},

			handleDelete(row, index) {
				this.$confirm('此操作将永久删除编号为' + row.id + '的数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					del(row.id).then(res => {
						if (res.code == '201') {
							this.$message({
								message: res.msg,
								type: 'success'
							});
						} else {
							this.$message.error(res.msg);
						}
					}).catch(err => {
						console.error(err);
						this.$message.error('操作异常，请联系管理员！');
					})

					this.list.splice(index, 1)
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			handleFetchPv(pv) {
				fetchPv(pv).then(response => {
					this.pvData = response.data.pvData
					this.dialogPvVisible = true
				})
			},
			handleDownload() {
				this.downloadLoading = true
				import('@/vendor/Export2Excel').then(excel => {
					const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
					const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
					const data = this.formatJson(filterVal)
					excel.export_json_to_excel({
						header: tHeader,
						data,
						filename: 'table-list'
					})
					this.downloadLoading = false
				})
			},

			getSortClass: function(key) {
				const sort = this.listQuery.sort
				return sort === `+${key}` ? 'ascending' : 'descending'
			},
			// 字典表中获取对应角色下拉数据
			getDictList() {
				fetchDictList('USER_TYPE').then(res => {
					if (res.code == '200') {
						this.dictData = res.data;
					}
				}).catch(err => {
					this.$message({
						message: res.msg,
						type: 'error'
					});
				})
			},

			handleClose(formName) {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						this.$confirm('确定要提交表单吗？')
							.then(() => {
								this.loading = true;
								if (this.form.id == '') {
									this.insert();
								} else {
									this.edit();
								}
								this.loading = false;
								this.dialog = false;
							})
							.catch((err) => {
								console.log('error submit!!');
							});

					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			cancelForm() {
				this.loading = false;
				this.dialog = false;
				this.$refs['form'].resetFields();
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			insert() {
				this.form.createdBy = getToken();
				this.form.creationDate = new Date();
				add(this.form).then(res => {
					if (res.code == '201') {
						this.$message({
							message: res.msg,
							type: 'success'
						});
						this.getList();
					} else {
						this.$message.error(res.msg);
					}
				}).catch(err => {
					console.error(err);
					this.$message.error('操作异常，请联系管理员！');
				})
			},
			edit() {
				this.form.modifyBy = getToken();
				this.form.modifyDate = new Date();
				update(this.form).then(res => {
					if (res.code == '201') {
						this.$message({
							message: res.msg,
							type: 'success'
						});
						this.getList();
					} else {
						this.$message.error(res.msg);
					}
				}).catch(err => {
					console.error(err);
					this.$message.error('操作异常，请联系管理员！');
				})
			},

			handleAvatarSuccess(res, file) {
				this.imageUrl = URL.createObjectURL(file.raw);
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			//onchange:预览图片
			picturePreview(file, fileList) {
				// console.log("fffff", file.raw);
				//预览图片
				if (window.createObjectURL != undefined) {
					this.imageUrl = window.createObjectURL(file.raw);
				} else if (window.URL != undefined) {
					this.imageUrl = window.URL.createObjectURL(file.raw);
				} else if (window.webkitURL != undefined) {
					this.imageUrl = window.webkitURL.createObjectURL(file.raw);
				}
				this.file = file.raw;
			},
			//取消上传
			cancelUpload() {
				this.imageUrl = "";
				this.file = "";
			},
			//文件上传 async这里本来想设置同步，但是怎么也改不了同步，还是异步
			async uploadPic() {
				const formData = new FormData();
				formData.append("file", this.file);
				formData.append("fileType", "IMAGE");
				let picName = new Date().getTime() + "";
				formData.append("picName", picName);

				this.form.picPath = picName;

				uploadImg(formData).then(res => {
					console.log('uploadres==>', res)
				}).catch(err => {
					this.$message.error("上传失败");
				})
				this.imageUrl = "";
			},
			submitUpload() {
				console.log("图片上传");
				this.uploadPic();
			},

			/* 文件上传 */
			handleUpload(e) {
				/* hack判断当前文件是否为空 */
				let files = e.target.files || e.dataTransfer.files;
				if (!files.length) return;

				/* 创建一个form对象 */
				let formData = new FormData();
				formData.append('multipartFile', files[0]); // 添加到form对象中
				console.info('res=>', formData);
				console.info('files[0=>', files[0]);

				uploadImg(formData)
					.then(res => {
						console.info('res=>', res);
						this.form.picPath = res.data;
						this.picUrl = res.data;
					})
					.catch(err => {
						console.info('err=>', err);
					})
			},
		}
	}
</script>

<style scoped>
	.demo-drawer__footer {
		display: flex;
		margin: 0 30px;
	}

	.demo-drawer__footer button {
		flex: 1;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 58px;
		height: 58px;
		border: 1px solid;
		line-height: 58px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>